/*
 * p3236.cpp
 *
 *  Created on: 2013-4-23
 *      Author: zy
 */

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int n, v1, v2;
int f[2][501][51][2];
int h[301], p[301], s[301];
int main()
{
	int cas = 0;
	while (scanf("%d%d%d", &v1, &v2, &n))
	{
		if (n == 0 && v1 == 0 && v2 == 0) break;
		cas++;
		for (int i = 1; i <= n; i++)
			scanf("%d%d%d", &p[i], &h[i], &s[i]);
		memset(f, 0, sizeof(f));
		for (int i = 1; i <= n; i++)
			for (int j = 0; j <= v1; j++)
				for (int k = 0; k <= v2; k++)
				{
					f[i % 2][j][k][0] = f[(i - 1) % 2][j][k][1] + h[i];
					if (s[i] == 0) f[i % 2][j][k][0] = max(f[i % 2][j][k][0],
							f[(i - 1) % 2][j][k][0]);
					if (j - p[i] >= 0) f[i % 2][j][k][0] = max(
							f[i % 2][j][k][0], f[(i - 1) % 2][j - p[i]][k][0]
									+ h[i]);
					if (k - p[i] >= 0) f[i % 2][j][k][0] = max(
							f[i % 2][j][k][0], f[(i - 1) % 2][j][k - p[i]][0]
									+ h[i]);
					if (s[i] == 0)
						f[i % 2][j][k][1] = f[(i - 1) % 2][j][k][1];
					else
						f[i % 2][j][k][1] = -INF;
					if (j - p[i] >= 0) f[i % 2][j][k][1] = max(
							f[i % 2][j][k][1], f[(i - 1) % 2][j - p[i]][k][1]
									+ h[i]);
					if (k - p[i] >= 0) f[i % 2][j][k][1] = max(
							f[i % 2][j][k][1], f[(i - 1) % 2][j][k - p[i]][1]
									+ h[i]);

				}
		if (f[n % 2][v1][v2][0] < 0)
			printf("Case %d: -1\n", cas);
		else
			printf("Case %d: %d\n", cas, f[n % 2][v1][v2][0]);
		printf("\n");
	}
	return 0;
}
